import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

class ComicService {
    boolean transactional = true
   
    def fileService

    def add(file, params, user){
    	def instance = new Comic(params)
    	instance.createdBy = user
    	
    	if(!instance.hasErrors()) {
			if(!file.isEmpty()) {
				def validate = fileService.validate(file, CH.config.comics.maxSizeComic)
	    		if(validate.ext != null) {
	    			def randomName = null
	    			def i = 0
	    			while(randomName == null || i < 3) {
	    				i ++
	    				randomName = fileService.addFile(file, "/comic/", validate.ext)
	    				
	    			} 
	    			
	    			if (randomName == null) {		//	No ha podido guardar el fichero en N intentos
	    				instance.errors.rejectValue('path',null,'no se ha podido guardar el fichero')
	    				log.debug "No se ha podido guardar la imagen con el nombre: ${randomName}.${validate.ext} y parametros: ${instance.toString()}"
		    			return [instance:instance]
	    			}

	    			instance.nameFile = randomName
	    			
	    		} else {
	    			instance.errors.rejectValue('path',null,validate.error)
	    			return [instance:instance]
	    		}
				
			}
	    	
	    	instance.save()
    	}
		return [instance:instance]
    }
    
    def update(file, params) {
    	def instance = Comic.get(params.id)
    	if (instance) {
            if (params.version) {
                def version = params.version.toLong()
                if (instance.version > version) {
                    instance.errors.rejectValue("version", "comic.optimistic.locking.failure", "Another user has updated this Comic while you were editing")
                    return instance
                }
            }
            instance.properties = params

            if(file != null && !file.isEmpty()) {
            	def path = CH.config.comics.path +"/comic/" 
            	fileService.deleteFile(path, instance.name +"."+instance.imageExt)
            	add (file, params)
            } else {
            	println "no se ha modificado el fichero"
            }
            	
            instance.save()
        	return instance
        }
        else {
        	return null
        }
    }
}
